#include "applib/lib_syscall.h"
#include <stdio.h>
#include "main.h"
#include <stdlib.h>
#include "string.h"
#include <getopt.h>     // 非标准c库函数，而是Newlib库
#include <sys/file.h>
#include "fs/file.h"
#include "dev/tty.h"

int main(int argc, char ** argv)
{
    if(argc == 1)
    {
        char msg_buff[128];
        fgets(msg_buff, sizeof(msg_buff), stdin);
        msg_buff[sizeof(msg_buff) - 1] = '\0';
        puts(msg_buff);
        return 0;
    }

    // 这里只是简单的判断，第二个参数是否以-x开头
    if(argc == 2 && argv[1][0] != '-')
    {
        puts(argv[1]);
        return 0;
    }


    int count = 1;
    int ch;                         // n后有: 代表-n后面有参数
                                    // h后没: 代表-h后面没参数
    while((ch = getopt(argc, argv, "n:h")) != -1)
    {
        if(ch == 'h')
        {
            puts("echo [-n count] messgae. echo something for count times.\n"
                    "if not have count, count = 1");
            optind = 1;
            return 0;
        }
        else if(ch == 'n')
        {
            count = atoi(optarg);
        }
        else if(ch == '?')
        {
            if(optarg)
            {
                fprintf(stderr, "Unknown option: -%d\n", optarg);
            }
            optind = 1;
            return -1;
        }
    }
    if(optind > argc - 1)
    {
        fprintf(stderr, "Message is empty\n");
        optind = 1;
        return -1;
    }

    char * msg = argv[optind];
    for(int i=0;i<count;i++)
    {
        puts(msg);
    }
    optind = 1;
    return 0;
}